package com.cyzy.server.service.impl;

import com.cyzy.common.exception.DateSequenceException;
import com.cyzy.common.exception.SelectNullException;
import com.cyzy.pojo.dto.RecruitCardDTO;
import com.cyzy.pojo.dto.RecruitCardUpdateDTO;
import com.cyzy.pojo.entity.RecruitCard;
import com.cyzy.pojo.entity.RecruitTag;
import com.cyzy.pojo.vo.RecruitCardVO;
import com.cyzy.server.dao.RecruitCardDao;
import com.cyzy.server.dao.RecruitCardTagsDao;
import com.cyzy.server.service.RecruitCardService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class RecruitCardServiceImpl implements RecruitCardService {

    @Autowired
    private RecruitCardDao recruitCardDao;
    @Autowired
    private RecruitCardTagsDao recruitCardTagsDao;

    /**
     * 将帖子的信息保存到数据库
     *
     * @param recruitCardDTO
     */
    @Override
    @Transactional
    public RecruitCard save(RecruitCardDTO recruitCardDTO) {
        RecruitCard recruitCard = new RecruitCard();

        //属性拷贝
        BeanUtils.copyProperties(recruitCardDTO, recruitCard);

        //默认设置为展示状态
        recruitCard.setDisplayed(1);

        //设置发布时间
        recruitCard.setPostTime(LocalDateTime.now());

        //status根据发布时间来设置
        String startTime = recruitCardDTO.getStartTime();
        String endTime = recruitCardDTO.getEndTime();
        String status = getStatus(startTime, endTime);
        if (status.equals("日期格式错误")) {
            throw new RuntimeException("日期格式错误");
        }
        recruitCard.setStatus(status);


        //除了tags以外的值插入表中
        recruitCardDao.insert(recruitCard);
        //获得insert语句产生的主键值
        Integer recruitCardId = recruitCard.getId();

        //处理招募帖子的tags
        List<RecruitTag> tags = recruitCardDTO.getTags();

        recruitCard.setTags(tags);

        if (tags != null && tags.size() > 0) {
            tags.forEach(recruitTag -> {
                recruitTag.setRecruitCardId(recruitCardId);
            });
            //向招募帖子的标签表插入数据
            recruitCardTagsDao.insertBatch(tags);
        }

        return recruitCard;
    }

    //根据开始时间和结束时间判断帖子的状态
    public static String getStatus(String startTime, String endTime) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date currentDate = new Date();
            Date startDate = dateFormat.parse(startTime);
            Date endDate = dateFormat.parse(endTime);

            if (startDate.after(endDate)) {
                throw new DateSequenceException("日期先后顺序错误");
            }

            if (currentDate.before(startDate)) {
                return "未开始";
            } else if (currentDate.after(endDate)) {
                return "已结束";
            } else {
                return "进行中";
            }
        } catch (ParseException e) {
//            e.printStackTrace();
//            return "日期格式错误";
            throw new DateSequenceException("日期格式错误");
        }
    }

    /**
     * 返回招募帖子的列表
     *
     * @return
     */
    @Transactional
    public List<RecruitCardVO> selectRecruitCardList() {
        List<RecruitCard> recruitCardList = recruitCardDao.selectRecruitCard();

        if(recruitCardList == null){
            throw new SelectNullException("拉取数据库信息为空");
        }

        List<RecruitCardVO> recruitCardVOS = new ArrayList<>();

        for (RecruitCard recruitCard : recruitCardList) {

            //获取招募帖子的id
            Integer id = recruitCard.getId();

            //获得招募活动的开始时间和结束时间然后判断帖子的状态
            String startTime = recruitCard.getStartTime();
            String endTime = recruitCard.getEndTime();
            String status = getStatus(startTime, endTime);

            if (!recruitCard.getStatus().equals(status)){
                //如果当前帖子的状态和现在查询的状态不同，就要重新设置状态
                recruitCardDao.updateRecruitCardStatus(status,id);
                //重新设置招募贴的status然后拷贝到VO里去
                recruitCard.setStatus(status);
            }

            //将每个recruitCard的元素拷贝到VO里返回
            RecruitCardVO recruitCardVO = new RecruitCardVO();
            BeanUtils.copyProperties(recruitCard, recruitCardVO);

            recruitCardVO.setRecruitCardId(id);
            //从tags表中查出招募贴的标签，然后返回
            List<RecruitTag> tags = recruitCardTagsDao.selectRecruitTagByHuntId(id);
            recruitCardVO.setTags(tags);
            recruitCardVOS.add(recruitCardVO);
        }

        return recruitCardVOS;
    }

    @Transactional
    public List<RecruitCardVO> selectRecruitCardList(int userId) {
        List<RecruitCard> recruitCardList = recruitCardDao.selectRecruitCardByPublisher(userId);
        List<RecruitCardVO> recruitCardVOS = new ArrayList<>();

        for (RecruitCard recruitCard : recruitCardList) {

            //获取招募帖子的id
            Integer id = recruitCard.getId();

            //获得招募活动的开始时间和结束时间然后判断帖子的状态
            String startTime = recruitCard.getStartTime();
            String endTime = recruitCard.getEndTime();
            String status = getStatus(startTime, endTime);

            if (!recruitCard.getStatus().equals(status)){
                //如果当前帖子的状态和现在查询的状态不同，就要重新设置状态
                recruitCardDao.updateRecruitCardStatus(status,id);
                //重新设置招募贴的status然后拷贝到VO里去
                recruitCard.setStatus(status);
            }

            //将每个recruitCard的元素拷贝到VO里返回
            RecruitCardVO recruitCardVO = new RecruitCardVO();
            BeanUtils.copyProperties(recruitCard, recruitCardVO);

            recruitCardVO.setRecruitCardId(id);
            //从tags表中查出招募贴的标签，然后返回
            List<RecruitTag> tags = recruitCardTagsDao.selectRecruitTagByHuntId(id);
            recruitCardVO.setTags(tags);
            recruitCardVOS.add(recruitCardVO);
        }

        return recruitCardVOS;
    }

    @Override
    @Transactional
    public RecruitCard selectRecruitCardById(Integer id) {
        RecruitCard recruitCard = recruitCardDao.selectRecruitCardById(id);

        if(recruitCard == null){
            throw new SelectNullException("拉取数据库信息为空");
        }
        //获得招募活动的开始时间和结束时间然后判断帖子的状态
        String startTime = recruitCard.getStartTime();
        String endTime = recruitCard.getEndTime();
        String status = getStatus(startTime, endTime);

        if (!recruitCard.getStatus().equals(status)){
            //如果当前帖子的状态和现在查询的状态不同，就要重新设置状态
            recruitCardDao.updateRecruitCardStatus(status,id);
            //重新设置招募贴的status然后拷贝到返回的实体类里去
            recruitCard.setStatus(status);
        }

        List<RecruitTag> recruitTags = recruitCardTagsDao.selectRecruitTagByHuntId(id);
        recruitCard.setTags(recruitTags);
        return recruitCard;
    }

    @Override
    @Transactional
    public RecruitCard updateRecruitCardById(Integer id, RecruitCardUpdateDTO recruitCardUpdateDTO) {
        RecruitCard recruitCard = new RecruitCard();
        recruitCard.setId(id);
        //将dto的数据拷贝到实体类里
        BeanUtils.copyProperties(recruitCardUpdateDTO, recruitCard);

        recruitCardDao.update(recruitCard);

        //删除对应id下的所有标签
        recruitCardTagsDao.deleteByRecruitCardId(id);

        //获取tag
        List<RecruitTag> tags = recruitCardUpdateDTO.getTags();
        if (tags != null && tags.size() > 0) {
            tags.forEach(recruitTag -> {
                recruitTag.setRecruitCardId(id);
            });
            //向招募标签表插入n条数据
            recruitCardTagsDao.insertBatch(tags);

        }


        //从数据库中查出修改后的实体类
        RecruitCard recruitCardAfterUpdate = recruitCardDao.selectRecruitCardById(id);

        if(recruitCardAfterUpdate == null){
            throw new SelectNullException("拉取数据库信息为空");
        }

        recruitCardAfterUpdate.setTags(tags);
        return recruitCardAfterUpdate;
    }


    @Override
    @Transactional
    public List<RecruitCardVO> selectRecruitCardListByUserId(Integer id) {

        List<RecruitCard> recruitCardList = recruitCardDao.selectRecruitCardByPublisher(id);
        List<RecruitCardVO> recruitCardVOS = new ArrayList<>();

        for (RecruitCard recruitCard : recruitCardList) {
            //将每个recruitCard的元素拷贝到VO里返回
            RecruitCardVO recruitCardVO = new RecruitCardVO();
            BeanUtils.copyProperties(recruitCard, recruitCardVO);
            //获取求职帖子的id
            Integer huntCardId = recruitCard.getId();

            recruitCardVO.setRecruitCardId(huntCardId);
            //从tags表中查出求职贴的标签，然后返回
            List<RecruitTag> tags = recruitCardTagsDao.selectRecruitTagByHuntId(huntCardId);

            recruitCardVO.setTags(tags);
            recruitCardVOS.add(recruitCardVO);
        }

        return recruitCardVOS;

    }

}
